from elementtree import ElementTree
from string import Template
import sys
import getopt
import feedparser

'''
for arg in sys.argv:
  print arg
    
tree = ElementTree.parse("/Users/mcj4/Desktop/subs.opml")

for outline in tree.findall("//outline"):
  print "* \"%s\":%s" % (outline.get('title'), outline.get('xmlUrl'))
'''

def renderFeed(url):
    d = feedparser.parse(url)
    if d.feed.has_key('title'):
        title   = Template("\n\n<h1>$title</h1>")
        print title.substitute(title = d['feed']['title']).encode('latin-1')
        content = Template("<div>$cont</div>")
        if len(d['entries']) >= 1:
            for entry in d['entries']:
                try:
                    print content.substitute(cont = entry['description']).encode('latin-1', 'ignore')
                except:
                    False
    
def getOutlineElements(file):
    tree = ElementTree.parse(file)
    return tree.findall("//outline")
    

def showOutlineElements(os):
    s = Template('$title $url')
    for o in os:
        title = o.get('title')
        url   = o.get('xmlUrl')
        if None != o.get('xmlUrl'):
            # print s.substitute(title = title, url = url)
            renderFeed(url)

def usage() :
    print
    print "OPMLRiver: Rendering news for offline reading"
    print "[-h, --help]           Prints this help and exits."
    print "[-d, --destination]    Chooses a destination directory for the generated news"
    print
    
def run():
    os = getOutlineElements("/Users/mcj4/Desktop/subs.opml")
    showOutlineElements(os)
    
def main(argv):                         
    try:                                
        opts, args = getopt.getopt(argv, "hd:", ["help", "destination"])
    except getopt.GetoptError:           
        usage()                          
        sys.exit(2)
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
    run()

if __name__ == "__main__":
    main(sys.argv[1:])